/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.core.model.objectify;

import com.google.inject.Inject;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import lt.ntec.danblog.server.core.model.Tag;
import lt.ntec.danblog.server.core.model.TagDAO;
import lt.ntec.danblog.server.core.model.TagFactory;
import lt.ntec.danblog.server.core.model.Taggable;

/**
 *
 * @author Tadas Šubonis (tadas.subonis@affecto.com)
 */
public class ObjectifyTagFactory implements TagFactory {

    @Inject
    private TagDAO tagDAO;

    @Override
    public Tag createTag(String value, Taggable parent) {
        Tag etag = tagDAO.getTagByValue(value);

        if (etag == null) {
            etag = new ObjectifyTag(value, parent);
        } else {
            etag.addParent(parent);
        }
        tagDAO.save(etag);
        return etag;
    }

    @Override
    public Set<Tag> createTagsFromString(String value, Taggable taggable) {
        List<String> tags = Arrays.asList(value.split("\\ "));
        Set<Tag> tr = new TreeSet<Tag>();
        for (String tg : tags) {
            tg = tg.trim();

            if (tg.isEmpty()) {
                continue;
            }

            Tag etag = createTag(tg, taggable);

            tr.add(etag);
        }
        return tr;
    }
}
